package com.ydgk.controller;

import com.ydgk.bean.*;
import com.ydgk.service.UserService;
import com.ydgk.tool.Tool;
import com.ydgk.vo.AddressInfo;
import com.ydgk.vo.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ModelAttribute
    public void getUser(@RequestParam(value = "uid", required = false, defaultValue = "0")Integer uid,Map map){
        if(uid != 0){
            User user = userService.findById(uid);
            map.put("user",user);
        }
    }

    @ModelAttribute
    public void getAddress(@RequestParam(value = "adid", required = false, defaultValue = "0")Integer adid,Map map){
        if(adid != 0){
            Address address = userService.getAddress(adid);
            map.put("address",address);
        }
    }

    @RequestMapping(value = "/toLogin")
    public String toLogin(@RequestParam("uname") String uname,
                          @RequestParam("upass") String upass,
                          @RequestParam(value = "cookie", required = false, defaultValue = "") String cookie, Map map, HttpServletResponse response, HttpSession session){
        Boolean isUemailExist = userService.checkUemailExist(uname);
        Boolean isUnickExist = userService.checkUnickExist(uname);
        Boolean isUphoneExist = userService.checkUphoneExist(uname);
        if(isUemailExist){
            User user = userService.findByUpassAndUemail(uname,upass);
            if(user != null){
                if(!cookie.equals("")){
                    Cookie cookieName = new Cookie("uname",uname);
                    Cookie cookiePass = new Cookie("upass",upass);
                    cookieName.setMaxAge(60 * 60 * 24 * 15);
                    cookiePass.setMaxAge(60 * 60 * 24 * 15);
                    cookieName.setPath("/");
                    cookiePass.setPath("/");
                    response.addCookie(cookieName);
                    response.addCookie(cookiePass);
                }
                session.setAttribute("user",user);
                return "redirect:/toPortal";
            }else{
                map.put("msg","密码错误！");
                return "Portal/login";
            }
        }else if(isUnickExist){
            User user = userService.findByUpassAndUnick(uname,upass);
            if(user != null){
                if(!cookie.equals("")){
                    Cookie cookieName = new Cookie("uname",uname);
                    Cookie cookiePass = new Cookie("upass",upass);
                    cookieName.setMaxAge(60 * 60 * 24 * 15);
                    cookiePass.setMaxAge(60 * 60 * 24 * 15);
                    cookieName.setPath("/");
                    cookiePass.setPath("/");
                    response.addCookie(cookieName);
                    response.addCookie(cookiePass);
                }
                session.setAttribute("user",user);
                return "redirect:/toPortal";
            }else{
                map.put("msg","密码错误！");
                return "Portal/login";
            }
        }else if(isUphoneExist){
            User user = userService.findByUpassAndUphone(uname,upass);
            if(user != null){
                if(!cookie.equals("")){
                    Cookie cookieName = new Cookie("uname",uname);
                    Cookie cookiePass = new Cookie("upass",upass);
                    cookieName.setMaxAge(60 * 60 * 24 * 15);
                    cookiePass.setMaxAge(60 * 60 * 24 * 15);
                    cookieName.setPath("/");
                    cookiePass.setPath("/");
                    response.addCookie(cookieName);
                    response.addCookie(cookiePass);
                }
                session.setAttribute("user",user);
                return "redirect:/toPortal";
            }else{
                map.put("msg","密码错误！");
                return "Portal/login";
            }
        }else{
            map.put("msg","该用户不存在！");
            return "Portal/login";
        }
    }

    @RequestMapping(value = "/toRegister" , method = RequestMethod.POST)
    public String toRegister(User user,@RequestParam("checkCode") String checkCode, HttpSession session, Map map){
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkCode)){
            Boolean isUemailExist = userService.checkUemailExist(user.getUemail());
            if(!isUemailExist){
                String unick = "用户"+Tool.getUUID();
                user.setUnick(unick);
                user.setRegtime(new Timestamp(System.currentTimeMillis()));
                userService.insert(user);
                map.put("msg","注册成功！您可以使用注册邮箱登录.");
                return "Portal/login";
            }else{
                map.put("error","此邮箱已注册！");
                return "Portal/register";
            }
        }else{
            map.put("error","验证码错误！");
            return "Portal/register";
        }
    }

    @RequestMapping(value = "/toCookieLogin")
    public String toCookieLogin(@RequestParam("uname") String uname,@RequestParam("upass") String upass, HttpSession session, HttpServletResponse response, Map map){
        User user = userService.findByUpassAndUemail(uname,upass);
        if(user != null){
            session.setAttribute("user",user);
            return "redirect:/toPortal";
        }else {
            user = userService.findByUpassAndUnick(uname,upass);
            if(user != null){
                session.setAttribute("user",user);
                return "redirect:/toPortal";
            }else {
                user = userService.findByUpassAndUphone(uname,upass);
                if(user != null){
                    session.setAttribute("user",user);
                    return "redirect:/toPortal";
                }else{
                    Cookie cookieName = new Cookie("uname",uname);
                    Cookie cookiePass = new Cookie("upass",upass);
                    cookieName.setMaxAge(0);
                    cookiePass.setMaxAge(0);
                    cookieName.setPath("/");
                    cookiePass.setPath("/");
                    response.addCookie(cookieName);
                    response.addCookie(cookiePass);
                    return "redirect:/toPortalLogin";
                }
            }
        }
    }


    @RequestMapping(value = "/updateUser")
    public String toRegister(User user , HttpSession session){
        userService.updateById(user);
        session.setAttribute("user",user);
        return "redirect:/toUser";
    }

    @ResponseBody
    @RequestMapping(value = "/getAllProvince")
    public AjaxResult getAllProvince(){
      AjaxResult ajaxResult = new AjaxResult();
      List<Province> provinceList = userService.getAllPro();
      ajaxResult.setData(provinceList);
      ajaxResult.setSuccess(true);
      return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/getCityByPid")
    public AjaxResult getCityByPid(Integer pid){
        AjaxResult ajaxResult = new AjaxResult();
        List<City> cityList = userService.getCityByPid(pid);
        ajaxResult.setData(cityList);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/getDistrictByCid")
    public AjaxResult getDistrictByCid(Integer cid){
        AjaxResult ajaxResult = new AjaxResult();
        List<District> districtList = userService.getDistrictByCid(cid);
        ajaxResult.setData(districtList);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "/getAreaByDid")
    public AjaxResult getAreaByDid(Integer did){
        AjaxResult ajaxResult = new AjaxResult();
        List<Area> areaList = userService.getAreaByDid(did);
        ajaxResult.setData(areaList);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    @RequestMapping(value = "/insertAddress")
    public String insertAddress(Address address, HttpSession session){
        User user = (User)session.getAttribute("user");
        address.setU_uid(user.getUid());
        int count = userService.getAddCount(user.getUid());
        if(count == 0){
            address.setIspretermission(1);
        }else{
            address.setIspretermission(0);
        }
        userService.insertAddress(address);
        return "redirect:/toAddress";
    }

    @RequestMapping(value = "/insertAddress2")
    public String insertAddress2(Address address, HttpSession session){
        User user = (User)session.getAttribute("user");
        address.setU_uid(user.getUid());
        int count = userService.getAddCount(user.getUid());
        if(count == 0){
            address.setIspretermission(1);
        }else{
            address.setIspretermission(0);
        }
        userService.insertAddress(address);
        return "redirect:/toAccount";
    }

    @RequestMapping(value = "/deleteAddress")
    public String deleteAddress(Integer adid,Map map){
        try {
            userService.deleteAddress(adid);

        }catch (Exception e){
            map.put("msg","有订单使用此地址,无法删除！");
        }
        return "forward:/toAddress";
    }

    @RequestMapping(value = "/deleteAddress2")
    public String deleteAddress2(Integer adid, Map map){
        try {
            userService.deleteAddress(adid);

        }catch (Exception e){
            map.put("msg","有订单使用此地址,无法删除！");
        }
        return "forward:/toAccount";
    }

    @ResponseBody
    @RequestMapping(value = "/getAddress")
    public AjaxResult getAddress(Integer adid){
        Address address = userService.getAddress(adid);
        AddressInfo addressInfo = userService.getAddressInfo(address);
       AjaxResult ajaxResult = new AjaxResult();
       ajaxResult.setData(addressInfo);
       ajaxResult.setSuccess(true);
       return ajaxResult;
    }

    @RequestMapping(value = "/updateAddress")
    public String updateAddress(Address address){
        userService.updateAddress(address);
        return "redirect:/toAddress";
    }

    @RequestMapping(value = "/updateAddress2")
    public String updateAddress2(Address address){
        userService.updateAddress(address);
        return "redirect:/toAccount";
    }

    @RequestMapping(value = "/setAddDefault")
    public String setAddDefault(Integer adid){
        userService.setAddDefault(adid);
        return "redirect:/toAccount";
    }

    @RequestMapping(value = "/updatePass")
    public String updatePass(User user) {
        userService.updateById(user);
        return "redirect:/toPortalLogin";
    }

    @RequestMapping(value = "/exit")
    public String exit(HttpSession session,HttpServletResponse response) {
        User user = (User)session.getAttribute("user");
        Cookie cookieName = new Cookie("uname",user.getUname());
        Cookie cookiePass = new Cookie("upass",user.getUpass());
        cookieName.setMaxAge(0);
        cookiePass.setMaxAge(0);
        cookieName.setPath("/");
        cookiePass.setPath("/");
        response.addCookie(cookieName);
        response.addCookie(cookiePass);
        session.invalidate();
        return "redirect:/toPortalLogin";
    }
}
